package com.app.configuration.web.websocket;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.Session;

import org.apache.log4j.Logger;

/**
 * @author Torui
 * 2018-09-25
 */
public class WebSocketManager {
	private static final Logger log = Logger.getLogger(WebSocketManager.class);
	//All WebSoket Session
    private static CopyOnWriteArraySet<Session> sessions = new CopyOnWriteArraySet<Session>();
    
    //Multiple Clients
  	private static Map<String,CopyOnWriteArraySet<Session>> customers = new Hashtable<String,CopyOnWriteArraySet<Session>>();
    
  	//Add All WebSoket Session And Customer's Clients
    public static void add(Session session) {
    	sessions.add(session);
    	String strUserId = (String)session.getUserProperties().get("strUserId");
    	CopyOnWriteArraySet<Session> clients = customers.get(strUserId);
		if(clients == null) {
			clients = new CopyOnWriteArraySet<Session>();
		}
		clients.add(session);
		customers.put(strUserId, clients);
	}
    
    //Remove Nominated WebSoket Session And Customer's Client
    public static  void remove(Session session) {
    	sessions.remove(session);
		String strUserId = (String)session.getUserProperties().get("strUserId");
		CopyOnWriteArraySet<Session> clients = customers.get(strUserId);
		if(clients != null) {
			clients.remove(session);
		}
		customers.put(strUserId, clients);
	}
    
    /**
     * Send Message to customers
     * @param strUserId 
     * @param message 
     */
    public static void sendMessage(String strUserId,String strMessage) {
    	//遍历所有链接，给相应的对象发送信息
    	Iterator<Session> itera= sessions.iterator();
    	while(itera.hasNext()){
    		Session session=itera.next();
			if(strUserId == null || strUserId.equals("")||checkRecUser(strUserId,session)) {
				try {
					if(session.isOpen()) {
						session.getBasicRemote().sendText(strMessage);
					}else {
						remove(session);
					}
				}catch(Exception e) {
					e.printStackTrace();
				}
			}
    	}
    }
    
    public static boolean checkRecUser(String strRecUser,Session session) {
		if(strRecUser.equals(session.getUserProperties().get("strId"))) {    		
    		return true;
    	}else if(strRecUser.equals(session.getUserProperties().get("strUserId"))) {    		
    		return true;
    	}else if(strRecUser.equals(session.getUserProperties().get("strName"))) {    		
    		return true;
    	}else if(strRecUser.equals(session.getUserProperties().get("strUnitId"))) {    		
    		return true;
    	}else if(strRecUser.equals(session.getUserProperties().get("strSchoolId"))) {
    		return true;    		
    	}else if(((String)session.getUserProperties().get("strTeamId")).indexOf(strRecUser)>0) {
    		return true;    		
    	}else if(((String)session.getUserProperties().get("strRoleId")).indexOf(strRecUser)>0) {
    		return true;    		
    	}		
		return false;
    	
    }
}
